import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import spsh from 'vite-plugin-simple-html'
import babel from '@rollup/plugin-babel'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const base = env.VITE_BASE
  const api = env.VITE_API
  const name = env.VITE_NAME
  const baseURL = env.VITE_BASEURL
  const systemBaseURL = env.VITE_SYSTEM_BASEURL

  function setProxy() {
    return {
      target: api,
      changeOrigin: true,
      rewrite: (path: string) => {
        console.log('\x1b[1;38;2;255;255;0mvite:proxy: \x1b[0m' + path + ' -> ' + api)
        return path
      }
    }
  }

  return {
    base,
    plugins: [
      vue(),
      spsh({
        minify: true,
        inject: {
          data: { name }
        }
      })
    ],
    server: {
      port: 6868,
      host: '0.0.0.0',
      proxy: {
        [baseURL]: setProxy(),
        [systemBaseURL]: setProxy()
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
              @use "./src/assets/scss/var.scss" as *;
            `
        }
      }
    },
    build: {
      rollupOptions: {
        plugins: [
          babel({
            extensions: ['.ts', '.vue'],
            babelHelpers: 'runtime',
            exclude: ['node_modules/**'],
            presets: [
              '@babel/preset-typescript',
              [
                '@babel/preset-env',
                {
                  useBuiltIns: 'usage',
                  corejs: 3
                }
              ]
            ],
            plugins: ['@babel/plugin-transform-runtime']
          })
        ]
      }
    }
  }
})
